package com.eunion.boot.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.eunion.core.LogUtil;
import com.eunion.web.admin.entity.AdminUser;

/**
 * 登录成功时执行.
 * 
 * @since 2017年1月1日
 */
@Component
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
	    throws IOException, ServletException {
		AdminUser loginUser = (AdminUser) authentication.getPrincipal();
		LogUtil.get(this.getClass()).debug("user:{} login",loginUser.getUsername());
//		request.getSession().setAttribute(Web.SESSION_USER, (new SessionUser(loginUser.getUsername(), loginUser.getUsername(), "")));//, user.getAuth()
		clearAuthenticationAttributes(request);
		handle(request, response, authentication);//如果是ajax就返回json
	}

	protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
	    throws IOException {
		String targetUrl = "/admin/";

		if (response.isCommitted()) {
			logger.debug("Response has already been committed. Unable to redirect to " + targetUrl);
			return;
		}

		getRedirectStrategy().sendRedirect(request, response, targetUrl);
	}

	protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response,Authentication authentication) {
//		String refererUrl = request.getHeader("Referer");  
//		 targetUrl = refererUrl；
//		 response.sendRedirect(targetUrl);
		 return "redirect:/admin/";
//		boolean isUser = false;
//		boolean isAdmin = false;
//		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
//		for (GrantedAuthority grantedAuthority : authorities) {
//			if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
//				isUser = true;
//				break;
//			} else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
//				isAdmin = true;
//				break;
//			}
//		}
//
//		if (isUser) {
//			return "/homepage.html";
//		} else if (isAdmin) {
//			return "/console.html";
//		} else {
//			throw new IllegalStateException();
//		}
	}

}
